package com.study.manage.utils;

import java.util.Random;

import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;

/**
 * 数字的工具类
 * 
 * 1.基于Guava的原始类型与byte[]的转换.
 *
 */
public class Numbers {

    public static byte[] longToBytes(long value) {
        return Longs.toByteArray(value);
    }

    public static long bytesToLong(byte[] bytes) {
        return Longs.fromByteArray(bytes);
    }

    public static byte[] intToBytes(int value) {
        return Ints.toByteArray(value);
    }

    public static int bytesToInt(byte[] bytes) {
        return Ints.fromByteArray(bytes);
    }

    public static long nextLong(Random rng, long n) {
        if (n <= 0) {
            throw new IllegalArgumentException("n must be positive");
        }
        if ((n & -n) == n) {
            // The 2^x checking just makes the generation faster because
            // directly using rng.nextLong() % n will be give uniform values
            // (assume all bits are good).
            // return (int)((n * (long)next(31)) >> 31);
        }
        long bits, val;
        do {
            bits = (rng.nextLong() << 1) >>> 1;
            val = bits % n;
        } while (bits - val + (n - 1) < 0L);
        return val;
    }
}
